import { getRandom, floatInRange, getRadiansByAngle } from '../utils/util';
import eventBus from '../utils/eventBus';

interface Options {
	canvasWidth: number;
	canvasHeight: number;
	ctx: WechatMiniprogram.CanvasRenderingContext.CanvasRenderingContext2D;
	cigaretteConfig: any;
}
class Cigarettes implements Options{
	public ctx;
	public canvasWidth;
	public canvasHeight;
	public cigaretteConfig: any;
	public ashParticle: any[];
	public ashDispearRows:number;
	public age:number;
	public burning: boolean;
	public isBounceing: boolean;
	public isBreatheIn: boolean;
	public bounceAnimateSpeed: number;
	public cRadians;
	// public currentBodyH:number;
	constructor(options: Options){
		this.canvasWidth = options.canvasWidth;
		this.canvasHeight = options.canvasHeight;
		this.ctx = options.ctx;
		this.ashParticle = [];
		// this.reset(options.cigaretteConfig);
		this.cigaretteConfig = options.cigaretteConfig;
		this.ashParticle = this.getAshParticle();
		this.ashDispearRows = 0;
		this.age = 0;
		this.burning = false;
		this.isBounceing = false;
		this.isBreatheIn = false;
		this.bounceAnimateSpeed = - this.cigaretteConfig.bounceStartSpeed;
		this.cRadians = 0;
		eventBus.on('light',(e)=>{
			this.burning = true;
			console.log(e,'点燃')
		})
		eventBus.on('bounce',(e)=>{
			this.isBounceing = true;
			this.cRadians = 0;
			console.log(e,'弹一下烟灰')
		})
		eventBus.on('breathe-in',(e)=>{
			this.isBreatheIn = true;
		})
		eventBus.on('breathe-out',(e)=>{
			this.isBreatheIn = false;
		})
	}

	reset(config:any){
		this.ashDispearRows = 0;
		this.cigaretteConfig = config;
		this.ashParticle = this.getAshParticle();
		// this.ashDispearRows = 0;
		this.age = 0;
		this.burning = false;
		this.isBounceing = false;
		this.isBreatheIn = false;
		this.bounceAnimateSpeed = - this.cigaretteConfig.bounceStartSpeed;
		this.cRadians = 0;
	}

	setBounceing(){
		const { ctx,cRadians } = this;
		const { x,y,w,h,bodyH } = this.cigaretteConfig;
		ctx.translate(x+w/2, y+bodyH); 
		ctx.rotate(cRadians);
		ctx.translate(-(x+w/2), -(y+bodyH));
	}

	setShadow(){
		const { ctx } = this;
		ctx.shadowOffsetX = 2;
		ctx.shadowOffsetY = 2;
		ctx.shadowBlur = 20;
		ctx.shadowColor = "rgba(0, 0, 0, 0.5)";
	}
	clearShadow(){
		const { ctx } = this;
		ctx.shadowOffsetX = 0;
		ctx.shadowOffsetY = 0;
		ctx.shadowBlur = 0;
	}

	draw(deltatime:number,currentBodyH:number):void{
		const { w, h, x, y, bottom, filterH, filterY, ringH, ringY, lifeTime, bodyH, bounceStartSpeed,  bodyColor,  filterColor,  ringColor } = this.cigaretteConfig;
		const { ctx } = this;

		if(this.burning){
			// 绘制烟灰条-随机的
			this.age = this.age + deltatime;
			// console.log(this.age,deltatime,'ageageageageage')
			this.drawAsh(currentBodyH,deltatime);
		}
		ctx.save();
		//绘制香烟体
		this.setShadow();
		ctx.fillStyle = bodyColor;
		if(this.isBounceing){
			this.cRadians = this.cRadians + this.bounceAnimateSpeed;
			this.bounceAnimateSpeed = this.bounceAnimateSpeed + 0.005*deltatime; //减速再加速
			if(this.cRadians>0){
				this.isBounceing = false;
				this.cRadians = 0;
				this.bounceAnimateSpeed = -bounceStartSpeed;
				ctx.rotate(this.cRadians);
			}else{
				this.setBounceing();
				// ctx.translate(x+w/2, y+h/2); // translate to rectangle center
				// ctx.rotate(this.cRadians);
				// ctx.translate(-(x+w/2), -(y+h/2));  // translate back
			}
			
		}

		ctx.fillRect(x, y + (bodyH - currentBodyH), w, currentBodyH+filterH);
		this.clearShadow();
		//绘制过滤嘴
		const w1 = w;
		const h1 = filterH;
		const x1 = x;
		const y1 = filterY;
		ctx.fillStyle = filterColor;
		ctx.fillRect(x1, y1, w1, h1);

		//绘制环带
		const w2 = w;
		const h2 = ringH;
		const x2 = x1;
		const y2 = ringY;
		ctx.fillStyle = ringColor;
		ctx.fillRect(x2, y2, w2, h2);
		// ctx.restore();

		//绘制光照渐变
		const lingrad = ctx.createLinearGradient(x, y, x + w, y);
		lingrad.addColorStop(0, "rgba(0,0,0,0)");
		lingrad.addColorStop(0.5, "rgba(0,0,0,0.3)");
		lingrad.addColorStop(1, "rgba(0,0,0,0)");
		ctx.fillStyle = lingrad;
		ctx.fillRect(x, y + (bodyH - currentBodyH), w, currentBodyH + filterH);
		if(this.burning){
			this.drawFireTop(currentBodyH);
		}
	}
	drawFireTop(currentBodyH:number){
		const { w,h,x,y,filterH,bodyH } = this.cigaretteConfig;
		const { ctx, canvasWidth, canvasHeight } = this;
		const fx = x;
		const fy = y + (bodyH - currentBodyH);
		// ctx.save();
		ctx.fillStyle = 'red';
		ctx.shadowOffsetX = 0;
		ctx.shadowOffsetY = 7;
		ctx.shadowBlur = 10;
		ctx.shadowColor = 'rgba(0,0,0,0.8)';
		ctx.fillRect(fx,fy,w,5);
		ctx.restore();
	}
	getAshColor(type: number){
		let color = ''
		switch(type){
			case 1:
				color = '#2d2d2d'
				break;
			case 2:
				color = '#434244'
				break;
			case 3:
				color = '#b0afb0'
				break;
			default: 
				color = '#e9e7e8'
		}
		return color
	}

	getAshParticle(){
		const particles = [];
		const { w,h,x,y,bodyH,lifeTime, ashRowCount } = this.cigaretteConfig;
		const ashBoxHeight = bodyH; //烟灰高度
		const rowCount = ashRowCount; //每行粒子数目
		const size = w/rowCount;
		const rows =  Math.ceil(ashBoxHeight/(size))
		const num = rows*rowCount;
		const lifeTimeSplit = Math.floor(lifeTime/rows);
		for(let i=0;i<num;i++){
			const rowIndex = Math.floor(i/rowCount); //计算属于第几行
			const columnIndex = i%rowCount;
			//==0 || == rowCount-1 为边缘粒子增加按照周期的随机掉落动画
			const sx = x + i%rowCount*size;
			const sy = y + rowIndex*size;
			let fillStyle = this.getAshColor(getRandom(1,5));
			const rotate = getRadiansByAngle(getRandom(0,360));
			const scale = 1 + getRandom(0,3)/10;
			const pItem:any = {
				x: sx,
				y: sy,
				size,
				fillStyle,
				rotate,
				scale,
				show: true,
				fall: false, //自动掉落
				isHandle: false,
				ashFallLifeTime: 1200,
				fallAge: 0,
				vx: (columnIndex == 0?-1:1)*floatInRange(0.1,0.3)
			}
			// if(columnIndex == 0 || columnIndex== rowCount-1){
			// 	pItem.fall = true;
			// 	pItem.fallStartTime = getRandom(Math.floor(lifeTime*1/5), Math.floor(lifeTime*4/5));
			// 	// console.log(pItem.fallStartTime,lifeTime,'lifeTime')
			// 	pItem.vx = (columnIndex == 0?-1:1)*floatInRange(0.05,0.09);
			// 	pItem.ashFallLifeTime = 1200;
			// 	// pItem.startVy = 
			// }

			particles.push(pItem);
		}
		return particles
	}

	drawAsh(currentBodyH:number,deltatime:number){
		const { w,h,x,y,bodyH,ashRowCount } = this.cigaretteConfig;
		const { ctx, canvasWidth, canvasHeight } = this;	
		const rowCount = ashRowCount; //每行粒子数目
		const size = w/rowCount;	
		const displayAshHeight = bodyH-currentBodyH;
		const displayRows = Math.ceil(displayAshHeight/size);
		if(this.isBounceing){
			console.log(displayRows,'displayRowsdisplayRowsdisplayRowsdisplayRows')
			this.ashDispearRows = displayRows>3?displayRows - 3:0;
		}
		//在已出现的烟灰粒子中随机边缘挑选需要掉落的
		for(let i=0;i<this.ashParticle.length;i++){
			const rowIndex = Math.floor(i/rowCount); //计算属于第几行
			const columnIndex = i%rowCount;
			const item = this.ashParticle[i];
			if([0,1,rowCount-1,rowCount-2].indexOf(columnIndex)>-1 && item.show && !item.fall && !item.isHandle){
				// console.log(i,'======index=========')
				if(columnIndex<getRandom(displayRows-5,displayRows-15)){
					item.isHandle = true;
					item.fall = getRandom(0,1)==0?true:false;
					item.fallAge = 0;
				}
			}
			if(this.isBounceing){
				//弹灰操作===挑选出大部分灰烬掉落处理
				if(item.show && !item.fall){
					if(rowIndex<displayRows-3){
						item.isHandle = true;
						item.fall = true;
						item.fallAge = 0;
						item.vx = -0.4;
					}
				}

			}
		}
		const particle = this.ashParticle.slice(0,displayRows*rowCount);
		particle.forEach((item,index)=>{
			if(!item.show){
				return
			}
			
			//按照渲染高度计算掉落时机
			// console.log(index,deltatime,'900000')
			if(item.fall){
				// if(index == 0)console.log(deltatime,item.fallStartTime,this.age,'900000')
				// if(this.age>item.fallStartTime && this.age < (item.fallStartTime+item.ashFallLifeTime)){
				if(item.fallAge < item.ashFallLifeTime){
					//更新位移
					item.x = item.x + item.vx*deltatime;
					item.y = item.y + (0.003)*deltatime*item.fallAge;
					// if(Math.floor(index/rowCount)>0)console.log((0.002)*deltatime,'vy')
					item.fallAge = item.fallAge + deltatime;
				}else{
					item.show = false;
				}
				// if(this.age > (item.fallStartTime+item.ashFallLifeTime)){
				// 	item.show = false;
				// }
			}
			// if(item.fall && this.age > item.fallStartTime+item.ashFallLifeTime){
			// 	item.show = false;
			// }
			const { x:sx, y:sy, fillStyle, rotate, size, scale } = item;
			ctx.save();
			ctx.shadowOffsetX = 2;
			ctx.shadowOffsetY = 2;
			ctx.shadowBlur = 2;
			ctx.shadowColor = "rgba(0, 0, 0, 0.5)";
			ctx.fillStyle = fillStyle;
			ctx.strokeStyle = '#000000';
			ctx.lineWidth = 0.5;//getRandom(1,2);

			if(this.isBounceing){
				this.setBounceing();
			}
			ctx.translate(sx+size/2, sy+size/2); // translate to rectangle center
			ctx.rotate(rotate); // rotate
			ctx.scale(scale,scale);
			ctx.translate(-(sx+size/2), -(sy+size/2));  // translate back
			

			ctx.fillRect(sx,sy,size,size);
			ctx.strokeRect(sx,sy,size,size);
			ctx.restore();
		})
		//渐变蒙版
		ctx.save();
		const lingrad = ctx.createLinearGradient(x, y, x + w, y);
		lingrad.addColorStop(0, "rgba(0,0,0,0)");
		lingrad.addColorStop(0.5, "rgba(255,255,255,0.3)");
		lingrad.addColorStop(1, "rgba(0,0,0,0)");
		ctx.fillStyle = lingrad;
		if(this.isBounceing){
			this.setBounceing();
		}
		ctx.fillRect(x, y+this.ashDispearRows*size, w, displayAshHeight-this.ashDispearRows*size);
		ctx.restore();
	}

}

export default Cigarettes